package com.ndkj.blog.utils;

import org.apache.http.HttpEntity;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

/**
 * @program: Blog
 * @description:
 * @author: liuyong
 * @create: 2021-08-09 21:59
 **/
public class GetAttribution {

    private CloseableHttpClient httpClient;
    private HttpGet httpGet;
    public static final String CONTENT_TYPE = "Content-Type";

    /**
     * 发送get请求
     * @param url 发送链接 拼接参数  http://localhost:8090/order?a=1
     * @return
     * @throws IOException
     */
    public String sendGet(String url) throws IOException {
        httpClient = HttpClients.createDefault();
        httpGet = new HttpGet(url);
        CloseableHttpResponse response = httpClient.execute(httpGet);
        String resp;
        try {
            HttpEntity entity = response.getEntity();
            resp = EntityUtils.toString(entity, "utf-8");
            EntityUtils.consume(entity);
        } finally {
            response.close();
        }
        //LoggerFactory.getLogger(getClass()).info(" resp:{}", resp);
        return resp;
    }

    /**
     * 创建发送post实体
     * @param charset     消息编码
     * @param contentType 消息体内容类型， HttpsClient.CONTENT_TYPE 调用传默认值
     * @param url         请求地址
     * @param data        发送数据
     * @return
     * @throws IOException
     */
    public String sendPost(String charset, String contentType, String url,String data) throws Exception {

        HttpClient httpclient = GetAttribution.getInstance();
        HttpPost httpPost = new HttpPost(url);

        httpPost.setHeader(CONTENT_TYPE, contentType);
        httpPost.setEntity(new StringEntity(data, charset));
        assert httpclient != null;
        CloseableHttpResponse response = (CloseableHttpResponse) httpclient.execute(httpPost);
        String resp = null;
        try {
            HttpEntity entity = response.getEntity();
            resp = EntityUtils.toString(entity, charset);
            EntityUtils.consume(entity);
        } finally {
            response.close();
        }
        //LoggerFactory.getLogger(getClass()).info("call [{}], param:{}, resp:{}", url, data, resp);
        return resp;
    }

    private static HttpClient getInstance() {
        return null;
    }
}

